import { Component, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { DirectoryItem, LibraryFileItem, FileLibraryServiceProxy, FileUploadServiceProxy, UpdateFileItemInput, UpdateFileNameInput } from '@shared/service-proxies/service-proxies';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { merge as _merge } from 'lodash-es';
import { finalize } from 'rxjs/operators';
import { FindingFileItem } from './file-finder-options';

@Component({
    templateUrl: './file-properties-edit-modal.component.html'
})
export class FilePropertiesEditModalComponent extends AppComponentBase {

    callback: {(file:LibraryFileItem):void};

    saving: boolean = false;

    data: UpdateFileItemInput;

    originName: string;

    showAlt = false;


    constructor(
        injector: Injector,
        public bsModalRef: BsModalRef,
        private _fileLibraryService: FileLibraryServiceProxy
    ) {
        super(injector);
        
        this.data = new UpdateFileItemInput();
    }

    close(): void {
        this.bsModalRef.hide();
    }

    shown(item:FindingFileItem): void {
        this.data = new UpdateFileItemInput();
        this.data.id = item.id;
        this.data.fileName = item.fileName;
        this.data.title = item.title;
        this.data.tags = item.tags;

        this.showAlt  = !item.icon;
    }

    save() {
        if (this.saving) {
            return;
        }
        this.saving = true;

        this._fileLibraryService.updateFileItem(this.data)
            .pipe(finalize(() => {
                this.saving = false;
            }))
            .subscribe(result => {
                this.notify.success(this.l('SavedSuccessfully'));
                this.callback && this.callback(result);
                this.close();
            });
    }
}
